package cc.rengu.redp.flowable.bizmodel.web.controller;


import cc.rengu.redp.common.annotation.Log;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.domain.RedpResponse;
import cc.rengu.redp.common.utils.RedpUtil;
import cc.rengu.redp.flowable.bizmodel.metadata.DictHandler;
import cc.rengu.redp.flowable.bizmodel.db.domain.BizCfgField;
import cc.rengu.redp.flowable.bizmodel.db.domain.BizCfgModel;
import cc.rengu.redp.flowable.bizmodel.web.service.BizCfgModelService;
import cc.rengu.redp.system.domain.DictRsVo;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务模型管理
 * @author xushitang
 */
@Slf4j
@RestController
@RequestMapping("/bizModel")
public class BizCfgModelController extends BaseController {

    @Autowired
    private BizCfgModelService bizCfgModelService;
    @Autowired
    private DictHandler dictHandler;

    @Log("查询业务模型列表")
    @GetMapping("/list")
    public Map<String, Object> modelList(QueryRequest request, BizCfgModel bizCfgModel) {
        return getDataTable(bizCfgModelService.findBizCfgModel(request, bizCfgModel));
    }

    @Log("查询单个业务模型")
    @GetMapping("/detail/{modelId}")
    public Map<String, Object> getModelDetail(@PathVariable String modelId) {
        return bizCfgModelService.getBizCfgModel(modelId);
    }

    @Log("查询流程定义")
    @GetMapping("/getProcesses")
    public Map<String, String> getAllProcesses(){
        return bizCfgModelService.getAllProcesses();
    }

    @Log("查询指定流程的结束事件")
    @GetMapping("/getEvent/{procDefId}")
    public Map<String, String> getEvent(@PathVariable String procDefId){
        return bizCfgModelService.getEndEvents(procDefId);
    }

    @Log("保存业务模型")
    @PostMapping("/add")
    public RedpResponse saveModel(BizCfgModel bizCfgModel, String bizCfgJson) {
        JSONArray bizCfgJsonArr = JSONArray.parseArray(bizCfgJson);
        List<BizCfgField> bizCfgFields = bizCfgJsonArr.toJavaList(BizCfgField.class);

        try {
            bizCfgModelService.saveBizCfgModel(bizCfgModel, bizCfgFields);
        } catch (Exception e) {
            String message = "保存业务模型失败";
            log.error(message, e);
            return RedpResponse.getInstance().failure().message(message);
        }

        return RedpResponse.getInstance().success().message("保存业务模型成功");
    }

    @Log("删除业务模型")
    @DeleteMapping("delete/{modelIds}")
    public RedpResponse deleteModels(@PathVariable String modelIds) {
        try {
            String[] ids = modelIds.split(StringPool.COMMA);
            bizCfgModelService.deleteBizCfgModel(ids);
        } catch (Exception e) {
            String message = "删除业务模型失败";
            log.error(message, e);
            return RedpResponse.getInstance().failure().message(message);
        }

        return RedpResponse.getInstance().success().message("删除业务模型成功");
    }

    @Log("获取指定业务模型数据字典")
    @GetMapping("/getModelDict/{modelId}/{fieldName}")
    public List<DictRsVo> getModelDict(@PathVariable String modelId, @PathVariable String fieldName) {
        List<DictRsVo> rsVos = new ArrayList<>();
        dictHandler.getDictList(modelId, fieldName).forEach(bizDict ->
            rsVos.add(new DictRsVo(bizDict.getDataUniqKey(), bizDict.getFieldValue()))
        );
        return rsVos;
    }

    @Log("获取业务模型数据字典对应的业务数据")
    @GetMapping("/getModelDictDetail/{uniqKey}")
    public String getModelDictDetail(@PathVariable String uniqKey){
        return dictHandler.getDictDetail(uniqKey);
    }

    @Log("可用模型查询")
    @GetMapping("/allAvailableModels")
    public Map<String, String> findAllAvailableModels() {
        Map<String, String> models = new HashMap<>();
        bizCfgModelService.findAllAvailableModels(RedpUtil.getCurrentUser()).forEach(bizCfgModel -> {
            models.put(bizCfgModel.getModelId().toString(), bizCfgModel.getModelName());
        });
        return models;
    }

    @Log("模型已索引字段查询")
    @GetMapping("/indexedFieldsInModel/{modelId}")
    public List<DictRsVo> findIndexedFieldsInModel(@PathVariable String modelId) {
        List<BizCfgField> bizCfgFields = bizCfgModelService.findIndexedFieldsInModel(modelId);
        List<DictRsVo> dictRsVos = new ArrayList<>();
        bizCfgFields.forEach(bizCfgField -> {
            dictRsVos.add(new DictRsVo(bizCfgField.getFieldName(), bizCfgField.getFieldDesc()));
        });
        return dictRsVos;
    }

    @Log("模型字段查询")
    @GetMapping("/fieldsInModel/{modelId}")
    public List<BizCfgField> findFieldsByModelId(@PathVariable String modelId){
        return bizCfgModelService.findFieldsInModel(modelId);
    }
}
